package com.vincent.kdp.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.vincent.baseapp.util.CommonUtil;
import com.vincent.baseapp.util.SPUtil;
import com.vincent.kdp.R;
import com.vincent.kdp.http.RequestCallBack;
import com.vincent.kdp.repository.CheckGoodsRepository;
import com.vincent.kdp.ui.bean.response.InStockOutput;
import com.vincent.kdp.util.InventoryApi;
import com.vincent.kdp.util.StringToHex;
import com.vincent.kdp.util.UhfDev;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SwitchCabinetActivity extends Activity {


    @Bind(R.id.bottom_line_tv)
    TextView bottomLineTv;
    @Bind(R.id.back_img) //返回
            ImageView backImg;
    @Bind(R.id.toolbar_center_tv)
    TextView toolbarCenterTv;
    @Bind(R.id.layout_toolbar_two)
    RelativeLayout layoutToolbarTwo;
    @Bind(R.id.buttonStart)
    Button buttonStart;
    @Bind(R.id.buttonReStart)
    Button buttonReStart;
    @Bind(R.id.linearLayoutButs)
    android.widget.LinearLayout linearLayoutButs;
    @Bind(R.id.textViewGoodshasChecked)
    TextView textViewGoodshasChecked;
    @Bind(R.id.textViewIp)
    TextView textViewIp;
    @Bind(R.id.unCheckDetailButton)
    Button unCheckDetailButton;
    @Bind(R.id.LinearLayout)
    android.widget.LinearLayout LinearLayout;

    TextView title;
    InventoryApi api;

    public Map<String, String> tagMap = new HashMap<String, String>();
    private Activity thisActivity;

    CheckGoodsRepository checkGoodsRepository=new CheckGoodsRepository();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch_cabinet); //HUAN
        ButterKnife.bind(this);
        thisActivity = this;

        connectUhf();

    }

    private boolean connectUhf() {
        api = InventoryApi.instance(this);
        String ip = SPUtil.getString("UHF_IP");
        textViewIp.setText(ip);
        api.setIp(ip);
        String ret = api.connectReader();
        api.setHandleFuncAndCallback(msgHandler);
        Log.d("UHF_DEV", ret);
        if ("0000".equals(ret)) {
            return true;
        } else {
            CommonUtil.showToast(this, ret);
            return false;
        }
    }

    public void calculatePercent() {
        textViewGoodshasChecked.setText(tagMap.size() + "个");
    }

    public Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String str = msg.getData().getString("msg");
            if ((null == str || 0 == str.length())
                    && ((UhfDev.MSG_TIMER != msg.what)
                    && (msg.what != UhfDev.MSG_PAUSE)
                    && (msg.what != UhfDev.MSG_RESUME)))
                return;
            if (msg.what == UhfDev.MSG_EPC) { // 标签内容
                String epc = str;
                addToListView(epc);
            } else if (msg.what == UhfDev.MSG_OPEN) { // 连接

            } else if (msg.what == UhfDev.MSG_TIMER) { // 定时器

            } else if (msg.what == UhfDev.MSG_PAUSE) { // 暂停
                api.stopInventory();
            } else if (msg.what == UhfDev.MSG_RESUME) { // 继续
                startInventory();
            } else { // 消息
            }
        }
    };

    private void addToListView(final String epcCount) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                synchronized (SwitchCabinetActivity.this) {
                    String[] tagArr = epcCount.split(";");
                    String epc = tagArr[0];

                    if (epc.length() < 26) {
                        Log.w("EPC", epc + "的编码格式不正确,要求大于26位");
                        return;
                    }
                    String hex = epc.substring(0, 26);
                    final String barCode = StringToHex.convertHexToString(hex);
//                    if (!tagMap.containsKey(barCode) && allGoodsMap.containsKey(barCode)) {
//                        tagMap.put(barCode, barCode);
//                    }
                    if (!tagMap.containsKey(barCode)) {
                        tagMap.put(barCode, barCode);
                    }
                    calculatePercent();

                }
            }
        });
    }

    private void startInventory() {
        if ("正在扫描".equals(buttonStart.getText())) {
            buttonStart.setText("开始扫描");
            api.stopInventory();
        } else {
            buttonStart.setText("正在扫描");
            api.startInventory();
        }

    }


    private void reStart() {
        tagMap.clear();

        SPUtil.remove("startQueryId");
        SPUtil.remove("allGoodsString");
        SPUtil.remove("hasCheckGoodsString");


    }

    private void getList() {

        String hasCheckGoodsString = saveCheckCode();
        getList(hasCheckGoodsString);
    }


    public String saveCheckCode() {
        StringBuffer hasCheckGoodsString = new StringBuffer();
        for (String v : tagMap.values()) {
            hasCheckGoodsString.append(v).append(",");
        }
        String hasCheckGoodsStringString = hasCheckGoodsString.toString();

        SPUtil.put("hasCheckGoodsString", hasCheckGoodsString);
        return hasCheckGoodsString.toString();
    }


    public void getList(String hasCheckGoodsString) {

        System.out.println("hasCheckGoodsString" + hasCheckGoodsString);
        //   hasCheckGoodsString = "0821707130001,0821707130002,0821707130003,0821707130004,0821707130005,0821707130006,0821707130007";

        checkGoodsRepository.listGoodsInStock(hasCheckGoodsString, new RequestCallBack<InStockOutput>() {
            @Override
            public void onSuccess(InStockOutput bean) {

                if (bean.getCode() == 0) {
                    Intent it = new Intent(SwitchCabinetActivity.this, ScanResultActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable("bean", bean);
                    it.putExtras(b);
                    startActivity(it);
                } else {

                }

            }

            @Override
            public void onFalse(String msg) {
                dialog(msg);
            }
        });
    }

    public void dialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SwitchCabinetActivity.this);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    @OnClick({R.id.back_img, R.id.buttonStart, R.id.buttonReStart, R.id.unCheckDetailButton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_img:
                finish();
                break;
            case R.id.buttonStart:
                startInventory();
                break;
            case R.id.buttonReStart:
                reStart();
                break;
            case R.id.unCheckDetailButton:
                getList();
                break;
        }
    }
}

